package com.situ.web.filter;

import com.situ.web.pojo.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("LoginFilter.init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("LoginFilter.doFilter");
        System.out.println("MyFilter1.doFilter");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        //HttpServletRequestWrapper wrapper = (HttpServletRequestWrapper) servletRequest;
        String servletPath = httpServletRequest.getServletPath();
        System.out.println("servletPath: " + servletPath);
        String method = httpServletRequest.getParameter("method");

        //对于要完成登录的请求 login.jsp  /user?method=login
        // 一些静态资源 html/css/js
        // 都不需要拦截验证
        if (servletPath.endsWith(".jpg")
                || servletPath.endsWith(".png")
                || servletPath.endsWith(".js")
                || servletPath.endsWith(".css")
                || servletPath.equals("/login.jsp")
                || servletPath.equals("/verifyCode")
                || servletPath.equals("/user") && method.equalsIgnoreCase("login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //需要拦截，判断有没有登录
        HttpSession session = httpServletRequest.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.jsp");
            return;
        }

        //如果不加这句话，Filter拦截所有的请求就停下来了
        //加了这句话代表方向，继续往后执行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("LoginFilter.destroy");
    }
}
